<template>
    <div class="login">
        <el-form :rules="rules" ref="ruleForm" label-width="100px" class="loginForm" :model="loginList">
            <el-form-item label="用户名"  prop="username">
                <el-input v-model="loginList.username" clearable></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginList.password" clearable show-password></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {userLogin } from '../request/api'
export default {
    data() {
        return {
            loginList: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'change' },
                    {
                        min: 6,
                        max: 16,
                        message: "长度在 6 到 16 个字符",
                        trigger: "blur",
                    },
                ]
            }
        }
    },
    //封装登录事件
    methods: {
        login() {
            this.$refs.ruleForm.validate((val) => {
                if (val) {
                    userLogin(this.loginList).then(res => {
                        console.log(res);
                        if (res.code == 200) {
                            this.$message.success(res.msg)
                            //先存储用户信息
                            this.$store.dispatch('changeUserAction', res.list)
                            
                            //跳转到首页
                            this.$router.push('/index')
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        }
    }
}
</script>

<style lang="less" scoped>
.login {
    width: 100vw;
    height: 100vh;
    background-image: url('../assets/images/pic.png');
    .loginForm {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 400px;
        height: 350px;
        margin: -150px 0 0 -170px;
    }
}
</style>